<template>
  <div class="login-container">
    <div class="shade"></div>
    <div class="login-content">
      <!--<div class="title">{{ webTitle }}</div>-->
      <div class="login-form">
        <a-form
          ref="formRef"
          :model="form"
          name="normal_login"
          class="login-form"
          :label-col="{ span: 4 }"
          style="width: 100%"
          @finish="onFinish"
        >
          <div class="form-item-title">用户名</div>
          <a-form-item name="username" :rules="[{ required: true, message: '请输入手机号!' }]">
            <a-input v-model:value="form.username" placeholder="请输入手机号" size="large">
              <template #prefix>
                <mobile-outlined class="icon" />
              </template>
            </a-input>
          </a-form-item>
          <div class="form-item-title">密码</div>
          <a-form-item name="password" :rules="[{ required: true, message: '请输入密码!' }]">
            <a-input
              v-model:value="form.password"
              type="password"
              placeholder="请输入密码"
              size="large"
            >
              <template #prefix>
                <lock-outlined class="icon" />
              </template>
            </a-input>
          </a-form-item>
          <template v-if="title === '修改密码'">
            <div class="form-item-title">新密码</div>
            <a-form-item name="newPassword" :rules="[{ required: true, validator: checkPassword }]">
              <a-input
                v-model:value="form.newPassword"
                type="password"
                placeholder="请输入新密码"
                size="large"
              >
                <template #prefix>
                  <lock-outlined class="icon" />
                </template>
              </a-input>
            </a-form-item>
            <div class="form-item-title">确认密码</div>
            <a-form-item
              name="rePassword"
              :rules="[{ required: true, validator: checkRepeatPassword }]"
            >
              <a-input
                v-model:value="form.rePassword"
                type="password"
                placeholder="请输入确认密码"
                size="large"
              >
                <template #prefix>
                  <lock-outlined class="icon" />
                </template>
              </a-input>
            </a-form-item>
          </template>

          <template v-if="title === '登录'">
            <div class="form-item-title">验证码</div>
            <div class="sms-code-container">
              <a-form-item name="captcha" :rules="[{ required: true, message: '请输入验证码!' }]">
                <a-input
                  v-model:value="form.captcha"
                  ref="captchaInput"
                  size="large"
                  placeholder="请输入验证码"
                >
                  <template #prefix>
                    <safety-certificate-outlined class="icon" />
                  </template>
                </a-input>
              </a-form-item>
              <div class="img-code">
                <img
                  v-if="captchaPath"
                  :src="'data:image/png;base64,' + captchaPath"
                  @click="getCaptcha()"
                />
              </div>
            </div>
          </template>
          <a-form-item>
            <a-button
              type="primary"
              html-type="submit"
              class="login-form-button"
              :loading="loading"
            >
              {{ title === '登录' ? '登 录' : '保 存' }}
            </a-button>
          </a-form-item>
          <!--<div class="btn-container">-->
          <!--  <div class="btn" @click="$handlePageJump('/register')">-->
          <!--    立即注册-->
          <!--  </div>-->
          <!--  <div class="btn" @click="$handlePageJump('/forget')">-->
          <!--    忘记密码-->
          <!--  </div>-->
          <!--</div>-->
        </a-form>
        <div class="copy-right">
          <!--<div class="copy-right-title">备案号xxx</div>-->
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import router from '@/router'
import { useRoute } from 'vue-router'
import useUserStore from '@/stores/user'
import { getCheckCodeImage, setPasswordWithoutCheckAccessTokenApi } from '@/api/user'
import md5 from 'md5'
import { webTitle } from '@/config'
import { message } from 'ant-design-vue'

const route = useRoute()
const userStore = useUserStore()
const captchaInput = ref()
const captchaPath = ref('')
const codeId = ref('')
const title = ref('登录')
const loading = ref(false)

const formRef = ref()
const form = ref({
  username: '',
  password: '',
  captcha: '',
  rePassword: '',
  newPassword: ''
})

function checkPassword(_rule, value) {
  if (value === '') {
    return Promise.reject('请输入新密码')
  } else {
    // 校验强密码 ^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,10}$
    // const objRegExp = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,20}$/
    const objRegExp = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*()_\-+]).{8,20}$/
    if (objRegExp.test(value)) {
      if (form.value.rePassword !== '') {
        formRef.value.validateFields('repeatPassword')
      }
      return Promise.resolve()
    } else {
      return Promise.reject('新密码必须包含大小写字母、数字、特殊字符的组合，长度在8-20之间')
      // return Promise.reject(
      //   '新密码必须包含大小写字母和数字的组合，可以使用特殊字符，长度在8-20之间'
      // )
    }
  }
}
function checkRepeatPassword(_rule, value) {
  if (value === '') {
    return Promise.reject('请输入确认密码')
  } else if (value !== form.value.newPassword) {
    return Promise.reject('两次输入不一致!')
  } else {
    return Promise.resolve()
  }
}

function getCaptcha() {
  getCheckCodeImage().then((res) => {
    codeId.value = res.SessionID
    captchaPath.value = res.Image
    form.value.captcha = ''
  })
}

function onFinish(values) {
  if (loading.value) {
    return
  }
  loading.value = true
  let params
  if (title.value === '登录') {
    params = {
      userName: values.username,
      password: md5(values.password),
      checkCode: values.captcha,
      loginType: 3, // 1用户名/密码登录,2短信验证码登录,3用户名/密码登录（带图片验证码
      loginSessionID: codeId.value
    }
    userStore
      .doLogin(params)
      .then(() => {
        loading.value = false
        if (userStore.userInfo.isAdministrator === '是') {
          router.replace('/home')
        } else {
          if (userStore.menuList.length > 0) {
            router.replace(`/projectTemplate/${userStore.menuList[0].id}`)
          } else {
            router.replace('/updatePassword')
          }
        }
      })
      .catch((err) => {
        // message.error(err.data)
        loading.value = false
        // if (err.data && err.data.indexOf('验证码') >= 0) {
        //   getCaptcha()
        // } else
        if (err.data === '新建账户必须修改默认密码。' || err.data === '密码已经超过使用期限。') {
          // message.error(err.data);
          title.value = '修改密码'
        } else {
          getCaptcha()
          captchaInput.value.focus()
        }
        console.log(err)
      })
  } else if (title.value === '修改密码') {
    params = {
      userName: values.username,
      newPassword: md5(values.newPassword),
      oldPassword: md5(values.password)
    }
    userStore.token = ''
    setPasswordWithoutCheckAccessTokenApi(params)
      .then(() => {
        message.success('修改成功,请使用新密码登录')
        loading.value = false
        title.value = '登录'
        form.value.password = values.newPassword
        form.value.captcha = ''
        getCaptcha()
      })
      .catch(() => {
        loading.value = false
      })
  }
}
onMounted(() => {
  getCaptcha()
})
</script>

<style scoped lang="less">
.login-container {
  width: 100vw;
  height: 100vh;
  position: relative;
  background-image: url('@/assets/images/login_bg.jpg');
  background-size: 100% 100%;
  .shade {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.3);
  }
  .login-content {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 2;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    width: 100%;
    height: 100%;
    .title {
      height: 50px;
      color: #fff;
      font-size: 30px;
      font-weight: bold;
      margin-bottom: 20px;
    }
    .login-form {
      width: 500px;
      background-color: #fff;
      box-shadow: 2px 2px 5px rgba(255, 255, 255, 0.5);
      border-radius: 10px;
      padding: 20px;
      @inputHeight: 50px;

      .form-item-title {
        color: #666;
        font-size: 18px;
        margin: 5px 0;
        font-weight: bold;
      }
      .sms-code-container {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20px;
        .ant-form-item {
          margin-bottom: 0;
          width: calc(100% - 40% - 10px);
        }
        .send-code-btn,
        .img-code {
          width: 40%;
          height: @inputHeight;
          border-radius: 4px;
          color: #999;
        }
        .img-code {
          overflow: hidden;
          img {
            width: 100%;
            height: 100%;
          }
        }
      }
      .ant-input-affix-wrapper-lg {
        height: @inputHeight;
        border-radius: 5px;
      }
      .agreement-container {
        margin: 20px 0 0;
        .link {
          color: #27a1ff;
          cursor: pointer;
        }
      }
      .login-form-button {
        width: 100%;
        height: @inputHeight;
        border-radius: 4px;
        font-weight: bold;
        font-size: 20px;
        margin-top: 20px;
      }
    }
    .copy-right {
      position: absolute;
      bottom: 20px;
      width: 500px;
      left: calc(50vw - 250px);
      color: #f2f2f2;
      text-align: center;
    }
  }
}
</style>
